//
//  CartoonMyDownLoadViewController.m
//  Cartoon
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonMyDownLoadViewController.h"
#import "CartoonMyDownLoadTableViewCell.h"
#import "CartoonMyDownLoad.h"
#import "CartoonALLMyDownLoad.h"
#import "CartoonMyDownLoadDetailsViewController.h"
#import "CartoonMyDownLoadAlreadyViewController.h"
@interface CartoonMyDownLoadViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *pictureDataArray;
@property (nonatomic, strong) NSMutableArray *pictureArr;
@property (nonatomic, strong) NSMutableDictionary *pictureDic;
@property (nonatomic, strong) NSMutableArray *FMDBDataArray;
@property (nonatomic, strong) NSMutableArray *FMDBDataNextArray;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *deleteArr;
@end

@implementation CartoonMyDownLoadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pictureDataArray = [NSMutableArray array];
    self.pictureArr = [NSMutableArray array];
    self.deleteArr = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[CartoonMyDownLoadTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult1 = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonALLMyDownLoad (name text , image text , cartoonID text primary key)"]];
        NSLog(@"creatResult1 = 创建是否成功 : %d",creatResult1);
    }
  

    self.FMDBDataArray = [NSMutableArray array];
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonALLMyDownLoad"];
    
    while ([set next]) {
        CartoonALLMyDownLoad *myALLDown = [[CartoonALLMyDownLoad alloc]init];
        myALLDown.name = [set stringForColumn:@"name"];
        myALLDown.image = [set stringForColumn:@"image"];
        myALLDown.cartoonID = [set stringForColumn:@"cartoonID"];
        [self.FMDBDataArray addObject:myALLDown];
    }
    
//    NSLog(@"FMDBDataArray = %@",self.FMDBDataArray);
    
    if ([self.whereAction isEqualToString:@"已下载"]) {
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
        UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
        label.text = @"您还没有下载哦";
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 101;
        label.hidden = YES;
        label.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:label];
    }else{
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
        UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
        label.text = @"您没有需要继续下载的哦";
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 101;
        label.hidden = YES;
        label.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:label];
    }
    if (self.FMDBDataArray.count == 0) {
        [self.view viewWithTag:101].hidden = NO;
    }
    
  
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    
    [self.tableView setEditing:editing animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.whereAction isEqualToString:@"已下载"]) {
    return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonMyDownLoad (name text , image text , cartoonID text primary key , cartoonPage text)"]];
        NSLog(@"创建是否成功 : %d",creatResult);
    }
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonMyDownLoad"];
    self.pageArray = [NSMutableArray array];
    CartoonALLMyDownLoad *allMyDown = [self.FMDBDataArray objectAtIndex:indexPath.row];
    while ([set next]) {
        CartoonMyDownLoad *down = [[CartoonMyDownLoad alloc]init];
        down.name = [set stringForColumn:@"name"];
        down.cartoonID = [set stringForColumn:@"cartoonID"];
        down.cartoonPage = [set stringForColumn:@"cartoonPage"];
        down.image = [set stringForColumn:@"image"];
        if ([[[down.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:allMyDown.cartoonID]) {
            
            [self.deleteArr addObject:down];
        }
    }
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        for (CartoonMyDownLoad *down in _deleteArr) {
            
        
        NSString *strr = [NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]];
        NSLog(@"%@",strr);
        //初始化Documents路径
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
        //初始化临时文件路径
        NSString *folderPath = [path stringByAppendingPathComponent:strr];
        //创建文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //判断temp文件夹是否存在
        
        NSLog(@"%@",folderPath);
        [fileManager removeItemAtPath:folderPath error:nil];
        
        
        
        BOOL isOpen = [[FMDB shareFMDB].db open];
        
        if (!isOpen) {
            NSLog(@"打开失败");
        }else{
            
        }
        
        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"delete from CartoonMyDownLoad where cartoonID = '%@'",down.cartoonID]];
            
            
    }
        
        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"delete from CartoonALLMyDownLoad where cartoonID = '%@'",allMyDown.cartoonID]];
        
        [self.FMDBDataArray removeObjectAtIndex:indexPath.row];
        if (self.FMDBDataArray.count == 0) {
            [self.view viewWithTag:101].hidden = NO;
        }
        [self.tableView reloadData];
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.FMDBDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonMyDownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    

    CartoonALLMyDownLoad *down = [self.FMDBDataArray objectAtIndex:indexPath.row];
    cell.myNameLabel.text = down.name;

    cell.myProgressView.hidden = YES;
   
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:down.image] placeholderImage:[UIImage imageNamed:@"5"]];
    
  
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.whereAction isEqualToString:@"继续下载"]) {
        CartoonMyDownLoadDetailsViewController *carVC = [[CartoonMyDownLoadDetailsViewController alloc] init];
        CartoonALLMyDownLoad *down = [self.FMDBDataArray objectAtIndex:indexPath.row];
        carVC.name = down.name;
        carVC.comic_id = down.cartoonID;
        carVC.myImageUrl = down.image;
        [self.navigationController pushViewController:carVC animated:YES];
    }else{
        CartoonMyDownLoadAlreadyViewController *alreadyDown = [[CartoonMyDownLoadAlreadyViewController alloc] init];
        CartoonALLMyDownLoad *down = [self.FMDBDataArray objectAtIndex:indexPath.row];
        alreadyDown.name = down.name;
        alreadyDown.comic_id = down.cartoonID;
        alreadyDown.myImageUrl = down.image;
        [self.navigationController pushViewController:alreadyDown animated:YES];
    }

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
